package three;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) {
        try {
            //创建Socket
            Socket s = new Socket("127.0.0.1", 9999);
            //开启两个线程，一个发消息，一个收消息
            new SendThread(s).start();
            new ReceiveThread(s).start();

            //等发送线程停下在往下执行
            try {
                new SendThread(s).join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //让接收线程停下
            new ReceiveThread(s).setFlag(false);

            //等接收线程停下来 在往下执行，断开连接
            try {
                new ReceiveThread(s).join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }
}
class SendThread extends Thread{
    private Socket s;

    public SendThread(Socket s) {
        super();
        this.s = s;
    }

    public void run(){
        Scanner sc = null;
        PrintStream ps = null;
        try {
            //键盘输入
            sc = new Scanner(System.in);
            ps = new PrintStream(s.getOutputStream());
            while(true){
                System.out.println("请输入要发送的消息：");
                String str = sc.nextLine();

                //给服务器发送信息
                ps.println(str);

                if("bye".equalsIgnoreCase(str)){
                    break;
                }
            }
            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ReceiveThread extends Thread{
    private Socket s;
    private boolean flag = true;

    public ReceiveThread(Socket s) {
        super();
        this.s = s;
    }
    public void run(){
        BufferedReader br =null;
        try {
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            while (flag){
                String line = br.readLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
